package com.xxx.yuedong.mine.service.impl;

import cn.hutool.core.map.MapUtil;
import com.xxx.yuedong.common.R;
import com.xxx.yuedong.mine.controller.form.UpdateRolePermissionForm;
import com.xxx.yuedong.mine.db.dao.RolePermissionDao;
import com.xxx.yuedong.mine.pojo.vo.RolePermissionListVO;
import com.xxx.yuedong.mine.service.RolePermissionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;

@Slf4j
@Service
public class RolePermissionServiceImpl implements RolePermissionService {
    @Autowired
    private RolePermissionDao rolePermissionDao;

    @Override
    public R list(HashMap param) {
        Integer page = MapUtil.getInt(param, "pageIndex");
        Integer length = MapUtil.getInt(param, "pageSize");
        Integer start = (page - 1) * length;
        param.put("start",start);
        param.put("length",length);
//        ArrayList<RolePermissionListVO> list = rolePermissionDao.list(param);
//        for (RolePermissionListVO rolePermissionListVO : list) {
//            System.out.println(rolePermissionListVO.toString());
//        }
        ArrayList<HashMap> list = rolePermissionDao.list(param);
        //System.out.println(list.get(0));
        Integer count = rolePermissionDao.listCount(param);
        return R.ok().put("list",list).put("totalCount",count);
    }

    @Override
    public R SearchRolePermissionInfo(Long roleId) {
        HashMap map = rolePermissionDao.SearchRolePermissionInfo(roleId);
        return R.ok().put("data",map);
    }

    @Override
    public R update(UpdateRolePermissionForm form) {
        Long[] addedIds = form.getAddedIds();
        Long[] removedIds = form.getRemovedIds();
        HashMap<String, Object> param = new HashMap<>();

        if (addedIds!=null){
            for (Long addedId : addedIds) {
                param.put("roleId",form.getRoleId());
                param.put("permissionId",addedId);
                rolePermissionDao.insert(param);
                param.clear();
            }
        }

        if (removedIds!=null){
            for (Long removedId : removedIds) {
                param.put("roleId",form.getRoleId());
                param.put("permissionId",removedId);
                rolePermissionDao.delete(param);
                param.clear();
            }
        }
        return R.ok();
    }
}
